package com.fumihiko.common.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.codec.binary.Base64;

public class CoderUtil {

	/**
	 * BASE64编码方式编码
	 * @param codes		需要编码加密的密码
	 * @return str		编码加密后的字符串
	 * @throws Exception
	 */
	public static String encryptBASE64(byte[] codes) throws Exception {
		return Base64.encodeBase64String(codes);
	}

	/**
	 * BASE64编码方式解码
	 * @param str		编码加密后的字符串
	 * @return codes	编码解码后的密码
	 * @throws Exception
	 */
	public static byte[] decryptBASE64(String str) throws Exception {
		return Base64.decodeBase64(str);
	}

	/**
	 * 将文件通过base64编码转化为字符串
	 * @param path     文件路径
	 * @return
	 * @throws Exception
	 */
	public static String fileEncodeByBase64(String path) throws Exception {
	    InputStream in = new FileInputStream(path);
	    BufferedInputStream bis = new BufferedInputStream(in);
	    ByteArrayOutputStream out = new ByteArrayOutputStream();
	    int c = bis.read();
	    while ((c != -1)) {
	        out.write(c);
	        c = bis.read();
	    }
	    bis.close();
	    out.close();
        in.close();
        byte[] buffer = out.toByteArray();
	    return encryptBASE64(buffer);
	}

	/**
	 * 将字符串通过base64解码码转化为二进制文件
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static byte[] fileDecoderByBase64(String file) throws Exception {
	    return decryptBASE64(file);
	}

}
